<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2 modal_main">
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
          <el-form-item label="材料名称" prop="materialName">
            <el-input v-model="queryParams.materialName" placeholder="请输入材料名称" clearable />
          </el-form-item>
          <el-form-item style="padding-left: 80px">
            <el-button size="small" type="primary" icon="search" @click="handleQuery">查询</el-button>
            <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Plus"
              @click="handleAdd">新增材料</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button size="small" type="primary" plain icon="Upload" @click="handleUpload">批量上传</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableData">
        <el-table-column label="材料名称" align="left" prop="materialName" width="180" fixed="left" />
        <el-table-column label="泊松比" align="left" prop="poissonRatio" />
        <el-table-column label="固体密度(kg/m³)" align="left" prop="solidDensity" />
        <el-table-column label="杨氏模量(Pa)" align="left" prop="youngModulus" />
        <el-table-column label="单位系统" align="left" prop="unitSystem" />
        <el-table-column label="操作" align="left" width="250" fixed="right">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button size="small" link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:remove']" link type="primary" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <pagination v-show="total > 0" style="margin-top: 0;" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" :total="total" :background="false"
          layout="total, sizes, prev, pager, next, jumper" @pagination="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="visible" :title="currentData?.id ? '修改固体材料' : '新增固体材料'" width="780px" append-to-body @close="cancel">
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="160px" size="small">
        <el-form-item label="材料名称" prop="materialName">
          <el-input placeholder="请输入材料名称	" v-model="form.materialName" />
        </el-form-item>
        <el-form-item label="泊松比实部" prop="poissonRatioReal">
          <el-input placeholder="请输入泊松比实部	" v-model="form.poissonRatioReal" />
        </el-form-item>
        <el-form-item label="泊松比虚部" prop="poissonRatioImag">
          <el-input placeholder="请输入泊松比虚部	" v-model="form.poissonRatioImag" />
        </el-form-item>
        <el-form-item label="固体密度实部(kg/m³)" prop="solidDensityReal">
          <el-input placeholder="请输入固体密度实部(kg/m³)" v-model="form.solidDensityReal" />
        </el-form-item>
        <el-form-item label="固体密度虚部(kg/m³)" prop="solidDensityImag">
          <el-input placeholder="请输入固体密度虚部(kg/m³)" v-model="form.solidDensityImag" />
        </el-form-item>
        <el-form-item label="杨氏模量实部(Pa)" prop="youngModulusReal">
          <el-input placeholder="请输入杨氏模量实部(Pa)" v-model="form.youngModulusReal" />
        </el-form-item>
        <el-form-item label="杨氏模量虚部(Pa)" prop="youngModulusImag">
          <el-input placeholder="请输入杨氏模量虚部(Pa)" v-model="form.youngModulusImag" />
        </el-form-item>
        <el-form-item label="单位系统" prop="unitSystem">
          <el-input placeholder="请输入单位系统" v-model="form.unitSystem" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="上传文件" v-model="uploadVisible" append-to-body @close="cancelUpload">
      <div style="display: flex;justify-content: center;">
        <el-upload :before-upload="handleBeforeUpload" accept=".dat" :on-change="handleChange" :on-remove="handleRemove" drag
          :file-list="fileList" :show-file-list="true" :auto-upload="false" :multiple="true" action="#" >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em style="color: blue;">点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传.dat文件</div>
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" @click="submitUpload">确 定</el-button>
          <el-button size="small" @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Oss">
import { getSolidMaterialList, addSolidMaterial, updateSolidMaterial, deleteSolidMaterial, uploadSolidMaterialFile } from '@/api/acousticsIsotropic/index.js';
const loading = ref(false);
const uploadVisible = ref(false);
const ossFormRef = ref(null);
const initFormData = {
  materialName: '',
  poissonRatioReal: '',
  poissonRatioImag: '',
  solidDensityReal: '',
  solidDensityImag: '',
  youngModulusReal: '',
  youngModulusImag: '',
  unitSystem: ''
};
const form = ref({ ...initFormData });
const queryParams = ref({
  // 查询参数
  pageNum: 1,
  pageSize: 10,
  materialName: '',
});
const fileList = ref([]);
const rules = ref({
  materialName: [{ required: true, message: '材料名称不能为空', trigger: 'blur' }],
  poissonRatioReal: [{ required: true, message: '泊松比实部不能为空', trigger: 'blur' }],
  poissonRatioImag: [{ required: true, message: '泊松比虚部不能为空', trigger: 'blur' }],
  solidDensityReal: [{ required: true, message: '固体密度实部不能为空', trigger: 'blur' }],
  solidDensityImag: [{ required: true, message: '固体密度虚部不能为空', trigger: 'blur' }],
  youngModulusReal: [{ required: true, message: '杨氏模量实部不能为空', trigger: 'blur' }],
  youngModulusImag: [{ required: true, message: '杨氏模量虚部不能为空', trigger: 'blur' }],
  unitSystem: [{ required: true, message: '单位系统不能为空', trigger: 'blur' }],
});
const tableData = ref([]);
const total = ref(0);
const visible = ref(false);
const currentData = ref(null);
const getList = async () => {
  loading.value = true;
  try {
    console.log(queryParams.value)
    const response = await getSolidMaterialList(queryParams.value);
    tableData.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};
const cancelUpload = () => {
  uploadVisible.value = false;
  fileList.value = [];
};
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error('请先选择要上传的文件');
    return;
  }
  const formData = new FormData();
  fileList.value.forEach((file) => {
    formData.append('files', file.raw);
  });
  // formData.append('files', file);
  try {
    // 假设有一个批量上传的API接口
    await uploadSolidMaterialFile(formData);
    ElMessage({
      type: 'success',
      message: '文件上传成功!',
    });
    uploadVisible.value = false;
    fileList.value = [];
    getList();
  } catch (error) {
    ElMessage.error('文件上传失败，请重试');
  }
};
const handleRemove = (event) => {
  const index = fileList.value.indexOf(event);
  if (index > -1) {
    fileList.value.splice(index, 1);
  }
};
const handleChange = (event) => {
  fileList.value.push(event);
};
const handleBeforeUpload = (file) => {
  const isDat = file.name.endsWith('.dat');
  if (!isDat) {
    ElMessage.error('只能上传.dat格式的文件!');
  }
  return isDat;
};
const resetQuery = () => {
  queryParams.value.materialName = '';
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getList();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
const handleAdd = () => {
  visible.value = true;
};
const handleUpload = () => {
  // 批量上传逻辑
  uploadVisible.value = true;
};
const handleDelete = (row) => {
  ElMessageBox.confirm('是否确认删除该材料？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteSolidMaterial(row.id);
    ElMessage({
      type: 'success',
      message: '删除成功!',
    });
    getList();
  }).catch(() => {
    // 取消删除
  });
};
const handleEdit = (row) => {
  Object.assign(form.value, row);
  currentData.value = row;
  visible.value = true;
};
const handleCurrentChange = (newPage) => {
  // queryParams.value.pageNum = newPage;
  getList();
};
const submitForm = () => {
  ossFormRef.value.validate(async (valid) => {
    if (valid) {
      if (currentData.value?.id) {
        await updateSolidMaterial(form.value);
        ElMessage({
          type: 'success',
          message: '修改成功!',
        });
      } else {
        form.value.id = null;
        await addSolidMaterial(form.value);
        ElMessage({
          type: 'success',
          message: '新增成功!',
        });
      }
      visible.value = false;
      Object.assign(form.value, initFormData);
      currentData.value = null;
      getList();
    }
  });
};
const cancel = () => {
  visible.value = false;
  currentData.value = null;
  Object.assign(form.value, initFormData);
};
onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.modal_main {
  height: calc(100vh - 180px);
  overflow: auto;
}

.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}

:deep(.el-upload) {
  display: block;
}
</style>